package ac.il.technion.c236369.hw4.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;

import org.apache.log4j.Logger;

import ac.il.technion.c236369.hw4.configuration.ServerConfig;
import ac.il.technion.c236369.hw4.core.queues.SocketQueue;

/**
 * @author Artem Barger and Maxim Aizenshtein
 *
 *	Class which handles incoming connections. Ones receive
 *	incoming connection puts corresponding socket inside
 *	relevant queue, to be handled later by SocketReader.
 *
 */
public class ConnectionListener extends Thread{

	private ServerSocket serverSocket;
	private boolean terminate = false;
	private final Logger log = Logger.getLogger( ConnectionListener.class);

	public ConnectionListener( ) {
		try {
			serverSocket = new ServerSocket( ServerConfig.getInstance().getProperties().getPort( ));
			serverSocket.setSoTimeout(5*1000);
		} catch (IOException e) {
			log.error(e);
		}
	}
	
	/**
	 * Start listen on server port for incoming connections. 
	 */
	public void startListen( ) {
		while ( !terminate ) {
			try {
				SocketQueue.getInstance().tryAdd( serverSocket.accept( ));
			} catch (SocketTimeoutException e) {
				log.info( "Reset socket listener.");
				try {
					// Sleep for half a second, and again wait for 
					// connection.
					Thread.sleep(5*100);
				} catch (InterruptedException e1) {
					log.error(e1);
				}
			} catch (IOException e) {
				log.error(e);
			}
		}
	}
	
	/**
	 * Force stop listen for incoming connections.
	 */
	public void stopListen( ) {
		terminate = false;
		log.info( "Listen thread has been terminated.");
	}

	@Override
	public void run() {
		startListen( );
	}
}
